package vincent.com.layouttest.service;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import vincent.com.layouttest.R;
import vincent.com.layouttest.util.LogUtil;

/**
 * Created by chenzhengwen on 2015/12/8.
 */
public class MyServiceActivities extends AppCompatActivity {
    private TextView mServiceReturn;
    private boolean mBound;
    private MyService mMyService;

    private ServiceConnection mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyService.MyBinder binder = (MyService.MyBinder)service;
            mMyService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_test);

        mServiceReturn = (TextView)findViewById(R.id.service_return);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent serviceIntent = new Intent("com.vincent.layouttest.service");
        bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mBound){
            unbindService(mServiceConn);
            mBound = false;
        }
    }

    public void randomInt(View v){
        mServiceReturn.setText(mMyService.getRandomNumber() + "");
        LogUtil.i(LogUtil.DEBUG_TAG, "outside service instance is " + mMyService.toString());
    }
}
